home *** CD-ROM | disk | FTP | other *** search
/ Chip 2007 January, February, March & April / Chip-Cover-CD-2007-02.iso / Pakiet bezpieczenstwa / mini Pentoo LiveCD 2006.1 / mpentoo-2006.1.iso / livecd.squashfs / usr / lib / python2.4 / pickle.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2005-10-18  |  36.9 KB  |  1,404 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.4)
  3.  
  4. '''Create portable serialized representations of Python objects.
  5.  
  6. See module cPickle for a (much) faster implementation.
  7. See module copy_reg for a mechanism for registering custom picklers.
  8. See module pickletools source for extensive comments.
  9.  
  10. Classes:
  11.  
  12.     Pickler
  13.     Unpickler
  14.  
  15. Functions:
  16.  
  17.     dump(object, file)
  18.     dumps(object) -> string
  19.     load(file) -> object
  20.     loads(string) -> object
  21.  
  22. Misc variables:
  23.  
  24.     __version__
  25.     format_version
  26.     compatible_formats
  27.  
  28. '''
  29. __version__ = '$Revision: 1.158 $'
  30. from types import *
  31. from copy_reg import dispatch_table
  32. from copy_reg import _extension_registry, _inverted_registry, _extension_cache
  33. import marshal
  34. import sys
  35. import struct
  36. import re
  37. import warnings
  38. __all__ = [
  39.     'PickleError',
  40.     'PicklingError',
  41.     'UnpicklingError',
  42.     'Pickler',
  43.     'Unpickler',
  44.     'dump',
  45.     'dumps',
  46.     'load',
  47.     'loads']
  48. format_version = '2.0'
  49. compatible_formats = [
  50.     '1.0',
  51.     '1.1',
  52.     '1.2',
  53.     '1.3',
  54.     '2.0']
  55. HIGHEST_PROTOCOL = 2
  56. mloads = marshal.loads
  57.  
  58. class PickleError(Exception):
  59.     '''A common base class for the other pickling exceptions.'''
  60.     pass
  61.  
  62.  
  63. class PicklingError(PickleError):
  64.     '''This exception is raised when an unpicklable object is passed to the
  65.     dump() method.
  66.  
  67.     '''
  68.     pass
  69.  
  70.  
  71. class UnpicklingError(PickleError):
  72.     '''This exception is raised when there is a problem unpickling an object,
  73.     such as a security violation.
  74.  
  75.     Note that other exceptions may also be raised during unpickling, including
  76.     (but not necessarily limited to) AttributeError, EOFError, ImportError,
  77.     and IndexError.
  78.  
  79.     '''
  80.     pass
  81.  
  82.  
  83. class _Stop(Exception):
  84.     
  85.     def __init__(self, value):
  86.         self.value = value
  87.  
  88.  
  89.  
  90. try:
  91.     from org.python.core import PyStringMap
  92. except ImportError:
  93.     PyStringMap = None
  94.  
  95.  
  96. try:
  97.     UnicodeType
  98. except NameError:
  99.     UnicodeType = None
  100.  
  101. MARK = '('
  102. STOP = '.'
  103. POP = '0'
  104. POP_MARK = '1'
  105. DUP = '2'
  106. FLOAT = 'F'
  107. INT = 'I'
  108. BININT = 'J'
  109. BININT1 = 'K'
  110. LONG = 'L'
  111. BININT2 = 'M'
  112. NONE = 'N'
  113. PERSID = 'P'
  114. BINPERSID = 'Q'
  115. REDUCE = 'R'
  116. STRING = 'S'
  117. BINSTRING = 'T'
  118. SHORT_BINSTRING = 'U'
  119. UNICODE = 'V'
  120. BINUNICODE = 'X'
  121. APPEND = 'a'
  122. BUILD = 'b'
  123. GLOBAL = 'c'
  124. DICT = 'd'
  125. EMPTY_DICT = '}'
  126. APPENDS = 'e'
  127. GET = 'g'
  128. BINGET = 'h'
  129. INST = 'i'
  130. LONG_BINGET = 'j'
  131. LIST = 'l'
  132. EMPTY_LIST = ']'
  133. OBJ = 'o'
  134. PUT = 'p'
  135. BINPUT = 'q'
  136. LONG_BINPUT = 'r'
  137. SETITEM = 's'
  138. TUPLE = 't'
  139. EMPTY_TUPLE = ')'
  140. SETITEMS = 'u'
  141. BINFLOAT = 'G'
  142. TRUE = 'I01\n'
  143. FALSE = 'I00\n'
  144. PROTO = '\x80'
  145. NEWOBJ = '\x81'
  146. EXT1 = '\x82'
  147. EXT2 = '\x83'
  148. EXT4 = '\x84'
  149. TUPLE1 = '\x85'
  150. TUPLE2 = '\x86'
  151. TUPLE3 = '\x87'
  152. NEWTRUE = '\x88'
  153. NEWFALSE = '\x89'
  154. LONG1 = '\x8a'
  155. LONG4 = '\x8b'
  156. _tuplesize2code = [
  157.     EMPTY_TUPLE,
  158.     TUPLE1,
  159.     TUPLE2,
  160.     TUPLE3]
  161. []([] if re.match('[A-Z][A-Z0-9_]+$', x) else _[1])
  162. del x
  163.  
  164. class Pickler:
  165.     
  166.     def __init__(self, file, protocol = None, bin = None):
  167.         '''This takes a file-like object for writing a pickle data stream.
  168.  
  169.         The optional protocol argument tells the pickler to use the
  170.         given protocol; supported protocols are 0, 1, 2.  The default
  171.         protocol is 0, to be backwards compatible.  (Protocol 0 is the
  172.         only protocol that can be written to a file opened in text
  173.         mode and read back successfully.  When using a protocol higher
  174.         than 0, make sure the file is opened in binary mode, both when
  175.         pickling and unpickling.)
  176.  
  177.         Protocol 1 is more efficient than protocol 0; protocol 2 is
  178.         more efficient than protocol 1.
  179.  
  180.         Specifying a negative protocol version selects the highest
  181.         protocol version supported.  The higher the protocol used, the
  182.         more recent the version of Python needed to read the pickle
  183.         produced.
  184.  
  185.         The file parameter must have a write() method that accepts a single
  186.         string argument.  It can thus be an open file object, a StringIO
  187.         object, or any other custom object that meets this interface.
  188.  
  189.         '''
  190.         if protocol is not None and bin is not None:
  191.             raise ValueError, "can't specify both 'protocol' and 'bin'"
  192.         
  193.         if bin is not None:
  194.             warnings.warn("The 'bin' argument to Pickler() is deprecated", DeprecationWarning)
  195.             protocol = bin
  196.         
  197.         if protocol is None:
  198.             protocol = 0
  199.         
  200.         if protocol < 0:
  201.             protocol = HIGHEST_PROTOCOL
  202.         elif protocol <= protocol:
  203.             pass
  204.         elif not protocol <= HIGHEST_PROTOCOL:
  205.             raise ValueError('pickle protocol must be <= %d' % HIGHEST_PROTOCOL)
  206.         
  207.         self.write = file.write
  208.         self.memo = { }
  209.         self.proto = int(protocol)
  210.         self.bin = protocol >= 1
  211.         self.fast = 0
  212.  
  213.     
  214.     def clear_memo(self):
  215.         '''Clears the pickler\'s "memo".
  216.  
  217.         The memo is the data structure that remembers which objects the
  218.         pickler has already seen, so that shared or recursive objects are
  219.         pickled by reference and not by value.  This method is useful when
  220.         re-using picklers.
  221.  
  222.         '''
  223.         self.memo.clear()
  224.  
  225.     
  226.     def dump(self, obj):
  227.         '''Write a pickled representation of obj to the open file.'''
  228.         if self.proto >= 2:
  229.             self.write(PROTO + chr(self.proto))
  230.         
  231.         self.save(obj)
  232.         self.write(STOP)
  233.  
  234.     
  235.     def memoize(self, obj):
  236.         '''Store an object in the memo.'''
  237.         if self.fast:
  238.             return None
  239.         
  240.         memo_len = len(self.memo)
  241.         self.write(self.put(memo_len))
  242.         self.memo[id(obj)] = (memo_len, obj)
  243.  
  244.     
  245.     def put(self, i, pack = struct.pack):
  246.         if self.bin:
  247.             if i < 256:
  248.                 return BINPUT + chr(i)
  249.             else:
  250.                 return LONG_BINPUT + pack('<i', i)
  251.         
  252.         return PUT + repr(i) + '\n'
  253.  
  254.     
  255.     def get(self, i, pack = struct.pack):
  256.         if self.bin:
  257.             if i < 256:
  258.                 return BINGET + chr(i)
  259.             else:
  260.                 return LONG_BINGET + pack('<i', i)
  261.         
  262.         return GET + repr(i) + '\n'
  263.  
  264.     
  265.     def save(self, obj):
  266.         pid = self.persistent_id(obj)
  267.         if pid:
  268.             self.save_pers(pid)
  269.             return None
  270.         
  271.         x = self.memo.get(id(obj))
  272.         if x:
  273.             self.write(self.get(x[0]))
  274.             return None
  275.         
  276.         t = type(obj)
  277.         f = self.dispatch.get(t)
  278.         if f:
  279.             f(self, obj)
  280.             return None
  281.         
  282.         
  283.         try:
  284.             issc = issubclass(t, TypeType)
  285.         except TypeError:
  286.             issc = 0
  287.  
  288.         if issc:
  289.             self.save_global(obj)
  290.             return None
  291.         
  292.         reduce = dispatch_table.get(t)
  293.         if reduce:
  294.             rv = reduce(obj)
  295.         else:
  296.             reduce = getattr(obj, '__reduce_ex__', None)
  297.             if reduce:
  298.                 rv = reduce(self.proto)
  299.             else:
  300.                 reduce = getattr(obj, '__reduce__', None)
  301.                 if reduce:
  302.                     rv = reduce()
  303.                 else:
  304.                     raise PicklingError("Can't pickle %r object: %r" % (t.__name__, obj))
  305.         if type(rv) is StringType:
  306.             self.save_global(obj, rv)
  307.             return None
  308.         
  309.         if type(rv) is not TupleType:
  310.             raise PicklingError('%s must return string or tuple' % reduce)
  311.         
  312.         l = len(rv)
  313.         if l <= l:
  314.             pass
  315.         elif not l <= 5:
  316.             raise PicklingError('Tuple returned by %s must have two to five elements' % reduce)
  317.         
  318.         self.save_reduce(obj = obj, *rv)
  319.  
  320.     
  321.     def persistent_id(self, obj):
  322.         pass
  323.  
  324.     
  325.     def save_pers(self, pid):
  326.         if self.bin:
  327.             self.save(pid)
  328.             self.write(BINPERSID)
  329.         else:
  330.             self.write(PERSID + str(pid) + '\n')
  331.  
  332.     
  333.     def save_reduce(self, func, args, state = None, listitems = None, dictitems = None, obj = None):
  334.         if not isinstance(args, TupleType):
  335.             if args is None:
  336.                 warnings.warn('__basicnew__ special case is deprecated', DeprecationWarning)
  337.             else:
  338.                 raise PicklingError('args from reduce() should be a tuple')
  339.         
  340.         if not callable(func):
  341.             raise PicklingError('func from reduce should be callable')
  342.         
  343.         save = self.save
  344.         write = self.write
  345.         if self.proto >= 2 and getattr(func, '__name__', '') == '__newobj__':
  346.             cls = args[0]
  347.             if not hasattr(cls, '__new__'):
  348.                 raise PicklingError('args[0] from __newobj__ args has no __new__')
  349.             
  350.             if obj is not None and cls is not obj.__class__:
  351.                 raise PicklingError('args[0] from __newobj__ args has the wrong class')
  352.             
  353.             args = args[1:]
  354.             save(cls)
  355.             save(args)
  356.             write(NEWOBJ)
  357.         else:
  358.             save(func)
  359.             save(args)
  360.             write(REDUCE)
  361.         if obj is not None:
  362.             self.memoize(obj)
  363.         
  364.         if listitems is not None:
  365.             self._batch_appends(listitems)
  366.         
  367.         if dictitems is not None:
  368.             self._batch_setitems(dictitems)
  369.         
  370.         if state is not None:
  371.             save(state)
  372.             write(BUILD)
  373.         
  374.  
  375.     dispatch = { }
  376.     
  377.     def save_none(self, obj):
  378.         self.write(NONE)
  379.  
  380.     dispatch[NoneType] = save_none
  381.     
  382.     def save_bool(self, obj):
  383.         if self.proto >= 2:
  384.             if not obj or NEWTRUE:
  385.                 pass
  386.             self.write(NEWFALSE)
  387.         elif not obj or TRUE:
  388.             pass
  389.         self.write(FALSE)
  390.  
  391.     dispatch[bool] = save_bool
  392.     
  393.     def save_int(self, obj, pack = struct.pack):
  394.         if self.bin:
  395.             if obj >= 0:
  396.                 if obj <= 255:
  397.                     self.write(BININT1 + chr(obj))
  398.                     return None
  399.                 
  400.                 if obj <= 65535:
  401.                     self.write('%c%c%c' % (BININT2, obj & 255, obj >> 8))
  402.                     return None
  403.                 
  404.             
  405.             high_bits = obj >> 31
  406.             if high_bits == 0 or high_bits == -1:
  407.                 self.write(BININT + pack('<i', obj))
  408.                 return None
  409.             
  410.         
  411.         self.write(INT + repr(obj) + '\n')
  412.  
  413.     dispatch[IntType] = save_int
  414.     
  415.     def save_long(self, obj, pack = struct.pack):
  416.         if self.proto >= 2:
  417.             bytes = encode_long(obj)
  418.             n = len(bytes)
  419.             if n < 256:
  420.                 self.write(LONG1 + chr(n) + bytes)
  421.             else:
  422.                 self.write(LONG4 + pack('<i', n) + bytes)
  423.             return None
  424.         
  425.         self.write(LONG + repr(obj) + '\n')
  426.  
  427.     dispatch[LongType] = save_long
  428.     
  429.     def save_float(self, obj, pack = struct.pack):
  430.         if self.bin:
  431.             self.write(BINFLOAT + pack('>d', obj))
  432.         else:
  433.             self.write(FLOAT + repr(obj) + '\n')
  434.  
  435.     dispatch[FloatType] = save_float
  436.     
  437.     def save_string(self, obj, pack = struct.pack):
  438.         if self.bin:
  439.             n = len(obj)
  440.             if n < 256:
  441.                 self.write(SHORT_BINSTRING + chr(n) + obj)
  442.             else:
  443.                 self.write(BINSTRING + pack('<i', n) + obj)
  444.         else:
  445.             self.write(STRING + repr(obj) + '\n')
  446.         self.memoize(obj)
  447.  
  448.     dispatch[StringType] = save_string
  449.     
  450.     def save_unicode(self, obj, pack = struct.pack):
  451.         if self.bin:
  452.             encoding = obj.encode('utf-8')
  453.             n = len(encoding)
  454.             self.write(BINUNICODE + pack('<i', n) + encoding)
  455.         else:
  456.             obj = obj.replace('\\', '\\u005c')
  457.             obj = obj.replace('\n', '\\u000a')
  458.             self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
  459.         self.memoize(obj)
  460.  
  461.     dispatch[UnicodeType] = save_unicode
  462.     if StringType == UnicodeType:
  463.         
  464.         def save_string(self, obj, pack = struct.pack):
  465.             unicode = obj.isunicode()
  466.             if self.bin:
  467.                 if unicode:
  468.                     obj = obj.encode('utf-8')
  469.                 
  470.                 l = len(obj)
  471.                 if l < 256 and not unicode:
  472.                     self.write(SHORT_BINSTRING + chr(l) + obj)
  473.                 else:
  474.                     s = pack('<i', l)
  475.                     if unicode:
  476.                         self.write(BINUNICODE + s + obj)
  477.                     else:
  478.                         self.write(BINSTRING + s + obj)
  479.             elif unicode:
  480.                 obj = obj.replace('\\', '\\u005c')
  481.                 obj = obj.replace('\n', '\\u000a')
  482.                 obj = obj.encode('raw-unicode-escape')
  483.                 self.write(UNICODE + obj + '\n')
  484.             else:
  485.                 self.write(STRING + repr(obj) + '\n')
  486.             self.memoize(obj)
  487.  
  488.         dispatch[StringType] = save_string
  489.     
  490.     
  491.     def save_tuple(self, obj):
  492.         write = self.write
  493.         proto = self.proto
  494.         n = len(obj)
  495.         if n == 0:
  496.             if proto:
  497.                 write(EMPTY_TUPLE)
  498.             else:
  499.                 write(MARK + TUPLE)
  500.             return None
  501.         
  502.         save = self.save
  503.         memo = self.memo
  504.         if n <= 3 and proto >= 2:
  505.             for element in obj:
  506.                 save(element)
  507.             
  508.             if id(obj) in memo:
  509.                 get = self.get(memo[id(obj)][0])
  510.                 write(POP * n + get)
  511.             else:
  512.                 write(_tuplesize2code[n])
  513.                 self.memoize(obj)
  514.             return None
  515.         
  516.         write(MARK)
  517.         for element in obj:
  518.             save(element)
  519.         
  520.         if id(obj) in memo:
  521.             get = self.get(memo[id(obj)][0])
  522.             if proto:
  523.                 write(POP_MARK + get)
  524.             else:
  525.                 write(POP * (n + 1) + get)
  526.             return None
  527.         
  528.         self.write(TUPLE)
  529.         self.memoize(obj)
  530.  
  531.     dispatch[TupleType] = save_tuple
  532.     
  533.     def save_empty_tuple(self, obj):
  534.         self.write(EMPTY_TUPLE)
  535.  
  536.     
  537.     def save_list(self, obj):
  538.         write = self.write
  539.         if self.bin:
  540.             write(EMPTY_LIST)
  541.         else:
  542.             write(MARK + LIST)
  543.         self.memoize(obj)
  544.         self._batch_appends(iter(obj))
  545.  
  546.     dispatch[ListType] = save_list
  547.     _BATCHSIZE = 1000
  548.     
  549.     def _batch_appends(self, items):
  550.         save = self.save
  551.         write = self.write
  552.         if not self.bin:
  553.             for x in items:
  554.                 save(x)
  555.                 write(APPEND)
  556.             
  557.             return None
  558.         
  559.         r = xrange(self._BATCHSIZE)
  560.         while items is not None:
  561.             tmp = []
  562.             for i in r:
  563.                 
  564.                 try:
  565.                     x = items.next()
  566.                     tmp.append(x)
  567.                 continue
  568.                 except StopIteration:
  569.                     items = None
  570.                     break
  571.                     continue
  572.                 
  573.  
  574.             
  575.             n = len(tmp)
  576.             if n > 1:
  577.                 write(MARK)
  578.                 for x in tmp:
  579.                     save(x)
  580.                 
  581.                 write(APPENDS)
  582.                 continue
  583.             None<EXCEPTION MATCH>StopIteration
  584.             if n:
  585.                 save(tmp[0])
  586.                 write(APPEND)
  587.                 continue
  588.  
  589.     
  590.     def save_dict(self, obj):
  591.         write = self.write
  592.         if self.bin:
  593.             write(EMPTY_DICT)
  594.         else:
  595.             write(MARK + DICT)
  596.         self.memoize(obj)
  597.         self._batch_setitems(obj.iteritems())
  598.  
  599.     dispatch[DictionaryType] = save_dict
  600.     if PyStringMap is not None:
  601.         dispatch[PyStringMap] = save_dict
  602.     
  603.     
  604.     def _batch_setitems(self, items):
  605.         save = self.save
  606.         write = self.write
  607.         if not self.bin:
  608.             for k, v in items:
  609.                 save(k)
  610.                 save(v)
  611.                 write(SETITEM)
  612.             
  613.             return None
  614.         
  615.         r = xrange(self._BATCHSIZE)
  616.         while items is not None:
  617.             tmp = []
  618.             for i in r:
  619.                 
  620.                 try:
  621.                     tmp.append(items.next())
  622.                 continue
  623.                 except StopIteration:
  624.                     items = None
  625.                     break
  626.                     continue
  627.                 
  628.  
  629.             
  630.             n = len(tmp)
  631.             if n > 1:
  632.                 write(MARK)
  633.                 for k, v in tmp:
  634.                     save(k)
  635.                     save(v)
  636.                 
  637.                 write(SETITEMS)
  638.                 continue
  639.             None<EXCEPTION MATCH>StopIteration
  640.             if n:
  641.                 (k, v) = tmp[0]
  642.                 save(k)
  643.                 save(v)
  644.                 write(SETITEM)
  645.                 continue
  646.  
  647.     
  648.     def save_inst(self, obj):
  649.         cls = obj.__class__
  650.         memo = self.memo
  651.         write = self.write
  652.         save = self.save
  653.         if hasattr(obj, '__getinitargs__'):
  654.             args = obj.__getinitargs__()
  655.             len(args)
  656.             _keep_alive(args, memo)
  657.         else:
  658.             args = ()
  659.         write(MARK)
  660.         if self.bin:
  661.             save(cls)
  662.             for arg in args:
  663.                 save(arg)
  664.             
  665.             write(OBJ)
  666.         else:
  667.             for arg in args:
  668.                 save(arg)
  669.             
  670.             write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
  671.         self.memoize(obj)
  672.         
  673.         try:
  674.             getstate = obj.__getstate__
  675.         except AttributeError:
  676.             stuff = obj.__dict__
  677.  
  678.         stuff = getstate()
  679.         _keep_alive(stuff, memo)
  680.         save(stuff)
  681.         write(BUILD)
  682.  
  683.     dispatch[InstanceType] = save_inst
  684.     
  685.     def save_global(self, obj, name = None, pack = struct.pack):
  686.         write = self.write
  687.         memo = self.memo
  688.         if name is None:
  689.             name = obj.__name__
  690.         
  691.         module = getattr(obj, '__module__', None)
  692.         if module is None:
  693.             module = whichmodule(obj, name)
  694.         
  695.         
  696.         try:
  697.             __import__(module)
  698.             mod = sys.modules[module]
  699.             klass = getattr(mod, name)
  700.         except (ImportError, KeyError, AttributeError):
  701.             raise PicklingError("Can't pickle %r: it's not found as %s.%s" % (obj, module, name))
  702.  
  703.         if klass is not obj:
  704.             raise PicklingError("Can't pickle %r: it's not the same object as %s.%s" % (obj, module, name))
  705.         
  706.         if self.proto >= 2:
  707.             code = _extension_registry.get((module, name))
  708.             if code:
  709.                 if code <= 255:
  710.                     write(EXT1 + chr(code))
  711.                 elif code <= 65535:
  712.                     write('%c%c%c' % (EXT2, code & 255, code >> 8))
  713.                 else:
  714.                     write(EXT4 + pack('<i', code))
  715.                 return None
  716.             
  717.         
  718.         write(GLOBAL + module + '\n' + name + '\n')
  719.         self.memoize(obj)
  720.  
  721.     dispatch[ClassType] = save_global
  722.     dispatch[FunctionType] = save_global
  723.     dispatch[BuiltinFunctionType] = save_global
  724.     dispatch[TypeType] = save_global
  725.  
  726.  
  727. def _keep_alive(x, memo):
  728.     '''Keeps a reference to the object x in the memo.
  729.  
  730.     Because we remember objects by their id, we have
  731.     to assure that possibly temporary objects are kept
  732.     alive by referencing them.
  733.     We store a reference at the id of the memo, which should
  734.     normally not be used unless someone tries to deepcopy
  735.     the memo itself...
  736.     '''
  737.     
  738.     try:
  739.         memo[id(memo)].append(x)
  740.     except KeyError:
  741.         memo[id(memo)] = [
  742.             x]
  743.  
  744.  
  745. classmap = { }
  746.  
  747. def whichmodule(func, funcname):
  748.     '''Figure out the module in which a function occurs.
  749.  
  750.     Search sys.modules for the module.
  751.     Cache in classmap.
  752.     Return a module name.
  753.     If the function cannot be found, return "__main__".
  754.     '''
  755.     mod = getattr(func, '__module__', None)
  756.     if mod is not None:
  757.         return mod
  758.     
  759.     if func in classmap:
  760.         return classmap[func]
  761.     
  762.     for name, module in sys.modules.items():
  763.         if module is None:
  764.             continue
  765.         
  766.         if name != '__main__' and getattr(module, funcname, None) is func:
  767.             break
  768.             continue
  769.     else:
  770.         name = '__main__'
  771.     classmap[func] = name
  772.     return name
  773.  
  774.  
  775. class Unpickler:
  776.     
  777.     def __init__(self, file):
  778.         '''This takes a file-like object for reading a pickle data stream.
  779.  
  780.         The protocol version of the pickle is detected automatically, so no
  781.         proto argument is needed.
  782.  
  783.         The file-like object must have two methods, a read() method that
  784.         takes an integer argument, and a readline() method that requires no
  785.         arguments.  Both methods should return a string.  Thus file-like
  786.         object can be a file object opened for reading, a StringIO object,
  787.         or any other custom object that meets this interface.
  788.         '''
  789.         self.readline = file.readline
  790.         self.read = file.read
  791.         self.memo = { }
  792.  
  793.     
  794.     def load(self):
  795.         '''Read a pickled object representation from the open file.
  796.  
  797.         Return the reconstituted object hierarchy specified in the file.
  798.         '''
  799.         self.mark = object()
  800.         self.stack = []
  801.         self.append = self.stack.append
  802.         read = self.read
  803.         dispatch = self.dispatch
  804.         
  805.         try:
  806.             while None:
  807.                 key = read(1)
  808.         except _Stop:
  809.             stopinst = None
  810.             return stopinst.value
  811.  
  812.  
  813.     
  814.     def marker(self):
  815.         stack = self.stack
  816.         mark = self.mark
  817.         k = len(stack) - 1
  818.         while stack[k] is not mark:
  819.             k = k - 1
  820.         return k
  821.  
  822.     dispatch = { }
  823.     
  824.     def load_eof(self):
  825.         raise EOFError
  826.  
  827.     dispatch[''] = load_eof
  828.     
  829.     def load_proto(self):
  830.         proto = ord(self.read(1))
  831.         if proto <= proto:
  832.             pass
  833.         elif not proto <= 2:
  834.             raise ValueError, 'unsupported pickle protocol: %d' % proto
  835.         
  836.  
  837.     dispatch[PROTO] = load_proto
  838.     
  839.     def load_persid(self):
  840.         pid = self.readline()[:-1]
  841.         self.append(self.persistent_load(pid))
  842.  
  843.     dispatch[PERSID] = load_persid
  844.     
  845.     def load_binpersid(self):
  846.         pid = self.stack.pop()
  847.         self.append(self.persistent_load(pid))
  848.  
  849.     dispatch[BINPERSID] = load_binpersid
  850.     
  851.     def load_none(self):
  852.         self.append(None)
  853.  
  854.     dispatch[NONE] = load_none
  855.     
  856.     def load_false(self):
  857.         self.append(False)
  858.  
  859.     dispatch[NEWFALSE] = load_false
  860.     
  861.     def load_true(self):
  862.         self.append(True)
  863.  
  864.     dispatch[NEWTRUE] = load_true
  865.     
  866.     def load_int(self):
  867.         data = self.readline()
  868.         if data == FALSE[1:]:
  869.             val = False
  870.         elif data == TRUE[1:]:
  871.             val = True
  872.         else:
  873.             
  874.             try:
  875.                 val = int(data)
  876.             except ValueError:
  877.                 val = long(data)
  878.  
  879.         self.append(val)
  880.  
  881.     dispatch[INT] = load_int
  882.     
  883.     def load_binint(self):
  884.         self.append(mloads('i' + self.read(4)))
  885.  
  886.     dispatch[BININT] = load_binint
  887.     
  888.     def load_binint1(self):
  889.         self.append(ord(self.read(1)))
  890.  
  891.     dispatch[BININT1] = load_binint1
  892.     
  893.     def load_binint2(self):
  894.         self.append(mloads('i' + self.read(2) + '\x00\x00'))
  895.  
  896.     dispatch[BININT2] = load_binint2
  897.     
  898.     def load_long(self):
  899.         self.append(long(self.readline()[:-1], 0))
  900.  
  901.     dispatch[LONG] = load_long
  902.     
  903.     def load_long1(self):
  904.         n = ord(self.read(1))
  905.         bytes = self.read(n)
  906.         self.append(decode_long(bytes))
  907.  
  908.     dispatch[LONG1] = load_long1
  909.     
  910.     def load_long4(self):
  911.         n = mloads('i' + self.read(4))
  912.         bytes = self.read(n)
  913.         self.append(decode_long(bytes))
  914.  
  915.     dispatch[LONG4] = load_long4
  916.     
  917.     def load_float(self):
  918.         self.append(float(self.readline()[:-1]))
  919.  
  920.     dispatch[FLOAT] = load_float
  921.     
  922.     def load_binfloat(self, unpack = struct.unpack):
  923.         self.append(unpack('>d', self.read(8))[0])
  924.  
  925.     dispatch[BINFLOAT] = load_binfloat
  926.     
  927.     def load_string(self):
  928.         rep = self.readline()[:-1]
  929.         for q in '"\'':
  930.             if rep.startswith(q):
  931.                 if not rep.endswith(q):
  932.                     raise ValueError, 'insecure string pickle'
  933.                 
  934.                 rep = rep[len(q):-len(q)]
  935.                 break
  936.                 continue
  937.         else:
  938.             raise ValueError, 'insecure string pickle'
  939.         self.append(rep.decode('string-escape'))
  940.  
  941.     dispatch[STRING] = load_string
  942.     
  943.     def load_binstring(self):
  944.         len = mloads('i' + self.read(4))
  945.         self.append(self.read(len))
  946.  
  947.     dispatch[BINSTRING] = load_binstring
  948.     
  949.     def load_unicode(self):
  950.         self.append(unicode(self.readline()[:-1], 'raw-unicode-escape'))
  951.  
  952.     dispatch[UNICODE] = load_unicode
  953.     
  954.     def load_binunicode(self):
  955.         len = mloads('i' + self.read(4))
  956.         self.append(unicode(self.read(len), 'utf-8'))
  957.  
  958.     dispatch[BINUNICODE] = load_binunicode
  959.     
  960.     def load_short_binstring(self):
  961.         len = ord(self.read(1))
  962.         self.append(self.read(len))
  963.  
  964.     dispatch[SHORT_BINSTRING] = load_short_binstring
  965.     
  966.     def load_tuple(self):
  967.         k = self.marker()
  968.         self.stack[k:] = [
  969.             tuple(self.stack[k + 1:])]
  970.  
  971.     dispatch[TUPLE] = load_tuple
  972.     
  973.     def load_empty_tuple(self):
  974.         self.stack.append(())
  975.  
  976.     dispatch[EMPTY_TUPLE] = load_empty_tuple
  977.     
  978.     def load_tuple1(self):
  979.         self.stack[-1] = (self.stack[-1],)
  980.  
  981.     dispatch[TUPLE1] = load_tuple1
  982.     
  983.     def load_tuple2(self):
  984.         self.stack[-2:] = [
  985.             (self.stack[-2], self.stack[-1])]
  986.  
  987.     dispatch[TUPLE2] = load_tuple2
  988.     
  989.     def load_tuple3(self):
  990.         self.stack[-3:] = [
  991.             (self.stack[-3], self.stack[-2], self.stack[-1])]
  992.  
  993.     dispatch[TUPLE3] = load_tuple3
  994.     
  995.     def load_empty_list(self):
  996.         self.stack.append([])
  997.  
  998.     dispatch[EMPTY_LIST] = load_empty_list
  999.     
  1000.     def load_empty_dictionary(self):
  1001.         self.stack.append({ })
  1002.  
  1003.     dispatch[EMPTY_DICT] = load_empty_dictionary
  1004.     
  1005.     def load_list(self):
  1006.         k = self.marker()
  1007.         self.stack[k:] = [
  1008.             self.stack[k + 1:]]
  1009.  
  1010.     dispatch[LIST] = load_list
  1011.     
  1012.     def load_dict(self):
  1013.         k = self.marker()
  1014.         d = { }
  1015.         items = self.stack[k + 1:]
  1016.         for i in range(0, len(items), 2):
  1017.             key = items[i]
  1018.             value = items[i + 1]
  1019.             d[key] = value
  1020.         
  1021.         self.stack[k:] = [
  1022.             d]
  1023.  
  1024.     dispatch[DICT] = load_dict
  1025.     
  1026.     def _instantiate(self, klass, k):
  1027.         args = tuple(self.stack[k + 1:])
  1028.         del self.stack[k:]
  1029.         instantiated = 0
  1030.         if not args and type(klass) is ClassType and not hasattr(klass, '__getinitargs__'):
  1031.             
  1032.             try:
  1033.                 value = _EmptyClass()
  1034.                 value.__class__ = klass
  1035.                 instantiated = 1
  1036.             except RuntimeError:
  1037.                 pass
  1038.             except:
  1039.                 None<EXCEPTION MATCH>RuntimeError
  1040.             
  1041.  
  1042.         None<EXCEPTION MATCH>RuntimeError
  1043.         if not instantiated:
  1044.             
  1045.             try:
  1046.                 value = klass(*args)
  1047.             except TypeError:
  1048.                 err = None
  1049.                 raise TypeError, 'in constructor for %s: %s' % (klass.__name__, str(err)), sys.exc_info()[2]
  1050.             except:
  1051.                 None<EXCEPTION MATCH>TypeError
  1052.             
  1053.  
  1054.         None<EXCEPTION MATCH>TypeError
  1055.         self.append(value)
  1056.  
  1057.     
  1058.     def load_inst(self):
  1059.         module = self.readline()[:-1]
  1060.         name = self.readline()[:-1]
  1061.         klass = self.find_class(module, name)
  1062.         self._instantiate(klass, self.marker())
  1063.  
  1064.     dispatch[INST] = load_inst
  1065.     
  1066.     def load_obj(self):
  1067.         k = self.marker()
  1068.         klass = self.stack.pop(k + 1)
  1069.         self._instantiate(klass, k)
  1070.  
  1071.     dispatch[OBJ] = load_obj
  1072.     
  1073.     def load_newobj(self):
  1074.         args = self.stack.pop()
  1075.         cls = self.stack[-1]
  1076.         obj = cls.__new__(cls, *args)
  1077.         self.stack[-1] = obj
  1078.  
  1079.     dispatch[NEWOBJ] = load_newobj
  1080.     
  1081.     def load_global(self):
  1082.         module = self.readline()[:-1]
  1083.         name = self.readline()[:-1]
  1084.         klass = self.find_class(module, name)
  1085.         self.append(klass)
  1086.  
  1087.     dispatch[GLOBAL] = load_global
  1088.     
  1089.     def load_ext1(self):
  1090.         code = ord(self.read(1))
  1091.         self.get_extension(code)
  1092.  
  1093.     dispatch[EXT1] = load_ext1
  1094.     
  1095.     def load_ext2(self):
  1096.         code = mloads('i' + self.read(2) + '\x00\x00')
  1097.         self.get_extension(code)
  1098.  
  1099.     dispatch[EXT2] = load_ext2
  1100.     
  1101.     def load_ext4(self):
  1102.         code = mloads('i' + self.read(4))
  1103.         self.get_extension(code)
  1104.  
  1105.     dispatch[EXT4] = load_ext4
  1106.     
  1107.     def get_extension(self, code):
  1108.         nil = []
  1109.         obj = _extension_cache.get(code, nil)
  1110.         if obj is not nil:
  1111.             self.append(obj)
  1112.             return None
  1113.         
  1114.         key = _inverted_registry.get(code)
  1115.         if not key:
  1116.             raise ValueError('unregistered extension code %d' % code)
  1117.         
  1118.         obj = self.find_class(*key)
  1119.         _extension_cache[code] = obj
  1120.         self.append(obj)
  1121.  
  1122.     
  1123.     def find_class(self, module, name):
  1124.         __import__(module)
  1125.         mod = sys.modules[module]
  1126.         klass = getattr(mod, name)
  1127.         return klass
  1128.  
  1129.     
  1130.     def load_reduce(self):
  1131.         stack = self.stack
  1132.         args = stack.pop()
  1133.         func = stack[-1]
  1134.         if args is None:
  1135.             warnings.warn('__basicnew__ special case is deprecated', DeprecationWarning)
  1136.             value = func.__basicnew__()
  1137.         else:
  1138.             value = func(*args)
  1139.         stack[-1] = value
  1140.  
  1141.     dispatch[REDUCE] = load_reduce
  1142.     
  1143.     def load_pop(self):
  1144.         del self.stack[-1]
  1145.  
  1146.     dispatch[POP] = load_pop
  1147.     
  1148.     def load_pop_mark(self):
  1149.         k = self.marker()
  1150.         del self.stack[k:]
  1151.  
  1152.     dispatch[POP_MARK] = load_pop_mark
  1153.     
  1154.     def load_dup(self):
  1155.         self.append(self.stack[-1])
  1156.  
  1157.     dispatch[DUP] = load_dup
  1158.     
  1159.     def load_get(self):
  1160.         self.append(self.memo[self.readline()[:-1]])
  1161.  
  1162.     dispatch[GET] = load_get
  1163.     
  1164.     def load_binget(self):
  1165.         i = ord(self.read(1))
  1166.         self.append(self.memo[repr(i)])
  1167.  
  1168.     dispatch[BINGET] = load_binget
  1169.     
  1170.     def load_long_binget(self):
  1171.         i = mloads('i' + self.read(4))
  1172.         self.append(self.memo[repr(i)])
  1173.  
  1174.     dispatch[LONG_BINGET] = load_long_binget
  1175.     
  1176.     def load_put(self):
  1177.         self.memo[self.readline()[:-1]] = self.stack[-1]
  1178.  
  1179.     dispatch[PUT] = load_put
  1180.     
  1181.     def load_binput(self):
  1182.         i = ord(self.read(1))
  1183.         self.memo[repr(i)] = self.stack[-1]
  1184.  
  1185.     dispatch[BINPUT] = load_binput
  1186.     
  1187.     def load_long_binput(self):
  1188.         i = mloads('i' + self.read(4))
  1189.         self.memo[repr(i)] = self.stack[-1]
  1190.  
  1191.     dispatch[LONG_BINPUT] = load_long_binput
  1192.     
  1193.     def load_append(self):
  1194.         stack = self.stack
  1195.         value = stack.pop()
  1196.         list = stack[-1]
  1197.         list.append(value)
  1198.  
  1199.     dispatch[APPEND] = load_append
  1200.     
  1201.     def load_appends(self):
  1202.         stack = self.stack
  1203.         mark = self.marker()
  1204.         list = stack[mark - 1]
  1205.         list.extend(stack[mark + 1:])
  1206.         del stack[mark:]
  1207.  
  1208.     dispatch[APPENDS] = load_appends
  1209.     
  1210.     def load_setitem(self):
  1211.         stack = self.stack
  1212.         value = stack.pop()
  1213.         key = stack.pop()
  1214.         dict = stack[-1]
  1215.         dict[key] = value
  1216.  
  1217.     dispatch[SETITEM] = load_setitem
  1218.     
  1219.     def load_setitems(self):
  1220.         stack = self.stack
  1221.         mark = self.marker()
  1222.         dict = stack[mark - 1]
  1223.         for i in range(mark + 1, len(stack), 2):
  1224.             dict[stack[i]] = stack[i + 1]
  1225.         
  1226.         del stack[mark:]
  1227.  
  1228.     dispatch[SETITEMS] = load_setitems
  1229.     
  1230.     def load_build(self):
  1231.         stack = self.stack
  1232.         state = stack.pop()
  1233.         inst = stack[-1]
  1234.         setstate = getattr(inst, '__setstate__', None)
  1235.         if setstate:
  1236.             setstate(state)
  1237.             return None
  1238.         
  1239.         slotstate = None
  1240.         if isinstance(state, tuple) and len(state) == 2:
  1241.             (state, slotstate) = state
  1242.         
  1243.         if state:
  1244.             
  1245.             try:
  1246.                 inst.__dict__.update(state)
  1247.             except RuntimeError:
  1248.                 for k, v in state.items():
  1249.                     setattr(inst, k, v)
  1250.                 
  1251.             
  1252.  
  1253.         None<EXCEPTION MATCH>RuntimeError
  1254.         if slotstate:
  1255.             for k, v in slotstate.items():
  1256.                 setattr(inst, k, v)
  1257.             
  1258.         
  1259.  
  1260.     dispatch[BUILD] = load_build
  1261.     
  1262.     def load_mark(self):
  1263.         self.append(self.mark)
  1264.  
  1265.     dispatch[MARK] = load_mark
  1266.     
  1267.     def load_stop(self):
  1268.         value = self.stack.pop()
  1269.         raise _Stop(value)
  1270.  
  1271.     dispatch[STOP] = load_stop
  1272.  
  1273.  
  1274. class _EmptyClass:
  1275.     pass
  1276.  
  1277. import binascii as _binascii
  1278.  
  1279. def encode_long(x):
  1280.     """Encode a long to a two's complement little-endian binary string.
  1281.     Note that 0L is a special case, returning an empty string, to save a
  1282.     byte in the LONG1 pickling context.
  1283.  
  1284.     >>> encode_long(0L)
  1285.     ''
  1286.     >>> encode_long(255L)
  1287.     '\\xff\\x00'
  1288.     >>> encode_long(32767L)
  1289.     '\\xff\\x7f'
  1290.     >>> encode_long(-256L)
  1291.     '\\x00\\xff'
  1292.     >>> encode_long(-32768L)
  1293.     '\\x00\\x80'
  1294.     >>> encode_long(-128L)
  1295.     '\\x80'
  1296.     >>> encode_long(127L)
  1297.     '\\x7f'
  1298.     >>>
  1299.     """
  1300.     if x == 0:
  1301.         return ''
  1302.     
  1303.     if x > 0:
  1304.         ashex = hex(x)
  1305.         njunkchars = 2 + ashex.endswith('L')
  1306.         nibbles = len(ashex) - njunkchars
  1307.         if nibbles & 1:
  1308.             ashex = '0x0' + ashex[2:]
  1309.         elif int(ashex[2], 16) >= 8:
  1310.             ashex = '0x00' + ashex[2:]
  1311.         
  1312.     else:
  1313.         ashex = hex(-x)
  1314.         njunkchars = 2 + ashex.endswith('L')
  1315.         nibbles = len(ashex) - njunkchars
  1316.         if nibbles & 1:
  1317.             nibbles += 1
  1318.         
  1319.         nbits = nibbles * 4
  1320.         x += 0x1L << nbits
  1321.         ashex = hex(x)
  1322.         njunkchars = 2 + ashex.endswith('L')
  1323.         newnibbles = len(ashex) - njunkchars
  1324.         if newnibbles < nibbles:
  1325.             ashex = '0x' + '0' * (nibbles - newnibbles) + ashex[2:]
  1326.         
  1327.         if int(ashex[2], 16) < 8:
  1328.             ashex = '0xff' + ashex[2:]
  1329.         
  1330.     if ashex.endswith('L'):
  1331.         ashex = ashex[2:-1]
  1332.     else:
  1333.         ashex = ashex[2:]
  1334.     binary = _binascii.unhexlify(ashex)
  1335.     return binary[::-1]
  1336.  
  1337.  
  1338. def decode_long(data):
  1339.     '''Decode a long from a two\'s complement little-endian binary string.
  1340.  
  1341.     >>> decode_long(\'\')
  1342.     0L
  1343.     >>> decode_long("\\xff\\x00")
  1344.     255L
  1345.     >>> decode_long("\\xff\\x7f")
  1346.     32767L
  1347.     >>> decode_long("\\x00\\xff")
  1348.     -256L
  1349.     >>> decode_long("\\x00\\x80")
  1350.     -32768L
  1351.     >>> decode_long("\\x80")
  1352.     -128L
  1353.     >>> decode_long("\\x7f")
  1354.     127L
  1355.     '''
  1356.     nbytes = len(data)
  1357.     if nbytes == 0:
  1358.         return 0x0L
  1359.     
  1360.     ashex = _binascii.hexlify(data[::-1])
  1361.     n = long(ashex, 16)
  1362.     if data[-1] >= '\x80':
  1363.         n -= 0x1L << nbytes * 8
  1364.     
  1365.     return n
  1366.  
  1367.  
  1368. try:
  1369.     from cStringIO import StringIO
  1370. except ImportError:
  1371.     __all__.extend
  1372.     __all__.extend
  1373.     from StringIO import StringIO
  1374. except:
  1375.     __all__.extend
  1376.  
  1377.  
  1378. def dump(obj, file, protocol = None, bin = None):
  1379.     Pickler(file, protocol, bin).dump(obj)
  1380.  
  1381.  
  1382. def dumps(obj, protocol = None, bin = None):
  1383.     file = StringIO()
  1384.     Pickler(file, protocol, bin).dump(obj)
  1385.     return file.getvalue()
  1386.  
  1387.  
  1388. def load(file):
  1389.     return Unpickler(file).load()
  1390.  
  1391.  
  1392. def loads(str):
  1393.     file = StringIO(str)
  1394.     return Unpickler(file).load()
  1395.  
  1396.  
  1397. def _test():
  1398.     import doctest
  1399.     return doctest.testmod()
  1400.  
  1401. if __name__ == '__main__':
  1402.     _test()
  1403.  
  1404.